﻿using Microsoft.AspNetCore.Http;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using Yuebon.Commons.Cache;
using Yuebon.Commons.Const;
using Yuebon.Commons.Helpers;
using Yuebon.Commons.Options;

namespace Yuebon.Commons.HttpContextUser
{
    public class AppCurrentUser:IUser
    {

        private readonly IHttpContextAccessor _accessor;

        public AppCurrentUser(IHttpContextAccessor accessor)
        {
            _accessor = accessor;
        }
        public UserInfo UserInfo=> GetUserInfo();
        public bool IsAuthenticated()
        {
            return _accessor.HttpContext?.User?.Identity?.IsAuthenticated ?? false;
        }
        public string GetToken()
        {
            var token = _accessor.HttpContext?.Request?.Headers["Authorization"].ObjToString().Replace("Bearer ", "");
            if (!token.IsNotEmptyOrNull())
            {
                return token;
            }
            return token;
        }
        public List<string> GetUserInfoFromToken(string ClaimType)
        {
            var jwtHandler = new JwtSecurityTokenHandler();
            var token = "";

            token = GetToken();
            // token校验
            if (token.IsNotEmptyOrNull() && jwtHandler.CanReadToken(token))
            {
                JwtSecurityToken jwtToken = jwtHandler.ReadJwtToken(token);

                return (from item in jwtToken.Claims
                        where item.Type == ClaimType
                        select item.Value).ToList();
            }

            return new List<string>() { };
        }
        public IEnumerable<Claim> GetClaimsIdentity()
        {
            if (_accessor.HttpContext == null) return ArraySegment<Claim>.Empty;

            if (!IsAuthenticated()) return GetClaimsIdentity(GetToken());

            var claims = _accessor.HttpContext.User.Claims.ToList();
            var headers = _accessor.HttpContext.Request.Headers;
            foreach (var header in headers)
            {
                claims.Add(new Claim(header.Key, header.Value));
            }

            return claims;
        }

        public IEnumerable<Claim> GetClaimsIdentity(string token)
        {
            if (token.IsNotEmptyOrNull())
            {
                var jwtHandler = new JwtSecurityTokenHandler();
                // token校验
                if (token.IsNotEmptyOrNull() && jwtHandler.CanReadToken(token))
                {
                    var jwtToken = jwtHandler.ReadJwtToken(token);

                    return jwtToken.Claims;
                }
            }

            return new List<Claim>();
        }

        public List<string> GetClaimValueByType(string ClaimType)
        {
            return (from item in GetClaimsIdentity()
                    where item.Type == ClaimType
                    select item.Value).ToList();
        }


        public UserInfo GetUserInfo()
        {
            YuebonCacheHelper yuebonCacheHelper = new YuebonCacheHelper();
            List<string> list = GetClaimValueByType("UserId");
            UserInfo userInfo = new UserInfo();
            if (list.Count > 0)
            {
                string userId = list.FirstOrDefault().ToString();
                userInfo = yuebonCacheHelper.Get<UserInfo>(CacheConst.KeyLoginUserInfo + userId);
            }
            return userInfo;
        }
    }
}
